import { expect } from '@jest/globals';
import * as execa from 'execa';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { commonConfig } from '../../plugins/common-config';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },

  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1,
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
  });

  const buffer = await fsExtra.readFile(path.resolve(project.getModule('entry').moduleRootPath(), 'oh-package.json5'));
  const parse = JSON5.parse(buffer.toString());
  parse.dependencies = {
    ...parse.dependencies,
    '@ohos/test_stage_ets_library': '1.0.0'
  };

  // eslint-disable-next-line max-len
  await fsExtra.writeFile(path.resolve(project.getModule('entry').moduleRootPath(), 'oh-package.json5'), JSON5.stringify(parse, null, 2), 'utf8');

  // 执行ohpm install
  await execa.command(commonConfig.ohpmInstallCommand, {
    cwd: path.resolve(project.getModule('entry').moduleRootPath())
  });

  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行hap编译构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

};

// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_Entry_Shared_Modules_HOS_api10_STAGE_001')
  .description('新模型工程entry-stage-eTS引用远程npm鸿蒙仓ets+npm包资源')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
